var mysql = require('mysql');
var Promise = require('bluebird');
var using = Promise.using;
Promise.promisifyAll(require('mysql/lib/Connection').prototype);
Promise.promisifyAll(require('mysql/lib/Pool').prototype);
var moment = require('moment');
var utils = require('./AlfredWorkflowUtils.js');

var pool = mysql.createPool({
	connectionLimit : 5,
	host : 'localhost',
	user : 'root',
	password : 'root',
	database : 'mysql'
});

var getConnection = function() {
	return pool.getConnectionAsync().disposer(function(connection) {
		// return connection.release();
		return connection.destroy();
	});
};

var executeSql = function(sql, params) {
	return using(getConnection(), function(connection) {
		return connection
				.queryAsync({
					sql : sql,
					timeout : 3000, // 3s
					values : params,
					typeCast : function(field, next) {
						if (field.type == 'DATETIME') {
							return moment(field.string()).format(
									'YYYY-MM-DD HH:mm:ss');
						}
						return next();
					}
				});
	});
};

module.exports = {
	executeSql : executeSql,
}
